package com.spdzen.support;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class WebContextUtils {
	public static final String ENCODING = "UTF-8";
	
	/**
	 * 每个请求都会在Request的Attribute中产生一个{@link com.speedweixin.support.RequestInfo}，
	 * 通过request.getAttribute({@link WebContextUtils#REQ_ATTR_REQUEST_INFO})获取。
	 */
	public static final String REQ_ATTR_REQUEST_INFO = "SIMPLE_REQUEST_INFO";
	
	/**
	 * 获取Request
	 * 
	 * @return
	 */
	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	public static HttpSession getSession() {
		return getRequest().getSession();
	}
	
	public static void setRequestInfo(RequestInfo info) {
		getRequest().setAttribute(REQ_ATTR_REQUEST_INFO, info);
	}
	
	public static void setRequestInfo(RequestInfo info, HttpServletRequest request) {
		request.setAttribute(REQ_ATTR_REQUEST_INFO, info);
	}
	
	public static RequestInfo getRequestInfo() {
		return (RequestInfo) getRequest().getAttribute(REQ_ATTR_REQUEST_INFO);
	}
	
	public static RequestInfo getRequestInfo(HttpServletRequest request) {
		return (RequestInfo) request.getAttribute(REQ_ATTR_REQUEST_INFO);
	}
}
